import { createPortal } from 'react-dom';
import { useEffect, useRef, useState } from 'react';
import './index.less';
import { useIntl } from 'umi';

const prefixCls = 'rds-popup';
const PopUp = (props) => {
  const { children, container = document.body, onClose, style } = props;
  const childrenRef = useRef(null);
  const [positionStyle, setPositionStyle] = useState({
    left: style?.left || 0,
    top: style?.top || 0,
  });
  // const intl = useIntl();
  useEffect(() => {
    // 检测是否超出窗口边界
    console.log(childrenRef.current.offsetHeight, window.innerWidth);
    if (positionStyle?.left && positionStyle?.top) {
      if (
        positionStyle.left + childrenRef.current.offsetWidth >
        window.innerWidth
      ) {
        setPositionStyle({
          ...positionStyle,
          left: window.innerWidth - childrenRef.current.offsetWidth + 'px',
        });
      }
      if (
        positionStyle.top + childrenRef.current.offsetHeight >
        window.innerHeight
      ) {
        setPositionStyle({
          ...positionStyle,
          top: window.innerHeight - childrenRef.current.offsetHeight + 'px',
        });
      }
    }
  }, []);
  return (
    <>
      {createPortal(
        <div className={`${prefixCls}`} onClick={(e) => onClose()}>
          <div
            className={`${prefixCls}-content`}
            onClick={(e) => e.stopPropagation()}
            style={{ ...style, ...positionStyle }}
            ref={childrenRef}
          >
            {children}
          </div>
          <div className={`${prefixCls}-mask`} />
        </div>,
        container,
      )}
    </>
  );
};
export default PopUp;
